package com.xxxy.action.department;
// 需要添加的导入
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONArray;

import com.xxxy.dao.DepartmentDao;
import com.xxxy.model.Department;
import com.xxxy.model.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/getAllDepartmentsPageServlet")
public class GetAllDepartmentsPageServlet extends HttpServlet {
	// 添加日志记录器
	private static final Logger logger = LoggerFactory.getLogger(GetAllDepartmentsPageServlet.class);
	private final DepartmentDao dao = new DepartmentDao();

	// GetAllDepartmentsPageServlet.java
	private int getIntParam(HttpServletRequest request, String paramName, int defaultValue) {
		try {
			String param = request.getParameter(paramName);
			return param != null ? Integer.parseInt(param) : defaultValue;
		} catch (NumberFormatException e) {
			logger.warn("参数[{}]格式错误，使用默认值{}", paramName, defaultValue);
			return defaultValue;
		}
	}

	private JSONObject convertToJson(Department dept) {
		JSONObject json = new JSONObject();
		json.put("departmentId", dept.getDepartmentId());
		json.put("departmentName", dept.getDepartmentName());
		json.put("departmentPid", dept.getDepartmentPid());
		json.put("departmentFlag", "0".equals(dept.getDepartmentFlag()) ? "启用" : "禁用");
		return json;
	}
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		response.setContentType("application/json;charset=utf-8");
		JSONObject result = new JSONObject();

		try {
			// 1. 获取分页参数
			int page = getIntParam(request, "page", 1);
			int limit = getIntParam(request, "limit", 10);
			Page pageObj = new Page(page, limit);

			// 2. 构建查询条件
			Department model = new Department();
			model.setDepartmentFlag(request.getParameter("cflag"));
			model.setDepartmentName(request.getParameter("cname"));
			model.setDepartmentPid(request.getParameter("pnames"));

			// 3. 执行查询
			List<Department> list = dao.getAllDataByPage(model, pageObj);
			int total = dao.getCount(model);

			// 4. 构建响应
			JSONArray data = new JSONArray();
			for(Department dept : list) {
				data.add(convertToJson(dept));
			}

			result.put("code", 0);
			result.put("msg", "success");
			result.put("count", total);
			result.put("data", data);

		} catch (Exception e) {
			handleError(response, 500, "服务器内部错误", e);
		}
		}

	// 辅助方法：统一错误处理
	private void handleError(HttpServletResponse response, int code, String msg, Exception e)
			throws IOException {
		logger.error(msg, e);
		JSONObject error = new JSONObject();
		error.put("code", code);
		error.put("msg", msg);
		response.setStatus(code);
		response.getWriter().print(error.toJSONString());
	}
}